#include <dspSimulator/instruction/shru.h>

bool SHRU::checkCondition(std::shared_ptr<DspMachine> dspMachine) {
    if (isCompactInstruction) {
        return true;
    } else {
        return checkStandardCondition(dspMachine);
    }
}

void SHRU::loadInstIRIntoJit(llvm::LLVMContext *llvmContext, llvm::Module *module,
                             std::shared_ptr<llvm::IRBuilder<>> irBuilder) {
    llvm::FunctionType *funcType = llvm::FunctionType::get(irBuilder->getVoidTy(), false);

    // --------------------------------- SHL (.unit) xsint, uint, dst---------------------------------------------
    {
        llvm::Function *shru = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "SHRUKind1",
                                                      module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", shru);
        irBuilder->SetInsertPoint(entryBB);

        auto dstRegPtr = getDstLoRegPtr(module, irBuilder);

        auto src2RegPtr = getSrc2LoRegPtr(module, irBuilder);
        auto src2 = irBuilder->CreateLoad(src2RegPtr);

        auto cst6 = getCstN(module, irBuilder, 6);
        auto ucst6 = irBuilder->CreateZExt(cst6, irBuilder->getInt32Ty());

        auto res = irBuilder->CreateLShr(src2, ucst6);
        irBuilder->CreateStore(res, dstRegPtr);
        irBuilder->CreateRetVoid();
    }

    // --------------------------------- SHL (.unit) xsint, ucst5, dst---------------------------------------------
    {
        llvm::Function *shruS = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "SHRUSKind3",
                                                       module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", shruS);
        irBuilder->SetInsertPoint(entryBB);

        auto dstRegPtr = getDstLoRegPtr(module, irBuilder);

        auto src2RegPtr = getSrc2LoRegPtr(module, irBuilder);
        auto src2 = irBuilder->CreateLoad(src2RegPtr, "src2Reg");

        auto cst5 = getCstN(module, irBuilder, 5);
        auto ucst5 = irBuilder->CreateZExt(cst5, irBuilder->getInt32Ty());

        auto res = irBuilder->CreateLShr(src2, ucst5);

        irBuilder->CreateStore(res, dstRegPtr);
        irBuilder->CreateRetVoid();
    }
}

std::shared_ptr<Instruction> SHRU::decode(std::shared_ptr<InstInfo> instInfo, u64 baseCycle) {
    std::shared_ptr<SHRU> shru;
    auto dspInstInfo = std::dynamic_pointer_cast<DspInstInfo>(instInfo);
    bool isStandardInst = dspInstInfo->isStandardInstruction();
    if (isStandardInst) {
        auto data = vectorToBitSet<32>(dspInstInfo->getBits());
        if (checkBits<10>(data, 2, 0b1001111000) && existStandardCondition(data)) {
            shru = std::make_shared<SHRU>(dspInstInfo->getAddress(), baseCycle);
            shru->creg_z = extractBits<4>(data, 28);
            shru->dst = extractBits<5>(data, 23).to_ulong();
            shru->src2 = extractBits<5>(data, 18).to_ulong();
            shru->src1 = extractBits<5>(data, 13).to_ulong();
            shru->x = data[12];
            shru->s = data[1];
            shru->p = data[0];
            if (shru->s == 0) {
                shru->funcUnit = FuncUnit::S1;
            } else {
                shru->funcUnit = FuncUnit::S2;
            }
            shru->instFormat = InstFormat::Kind1;
        } else if (checkBits<10>(data, 2, 0b1001101000) && existStandardCondition(data)) {
            shru = std::make_shared<SHRU>(dspInstInfo->getAddress(), baseCycle);
            shru->creg_z = extractBits<4>(data, 28);
            shru->dst = extractBits<5>(data, 23).to_ulong();
            shru->src2 = extractBits<5>(data, 18).to_ulong();
            shru->cst = extractBits<5>(data, 13).to_ulong();
            shru->x = data[12];
            shru->s = data[1];
            shru->p = data[0];
            if (shru->s == 0) {
                shru->funcUnit = FuncUnit::S1;
            } else {
                shru->funcUnit = FuncUnit::S2;
            }
            shru->instFormat = InstFormat::Kind3;
        }
    } else {
        auto data = vectorToBitSet<16>(dspInstInfo->getBits());
        if (dspInstInfo->getSAT() == 0 && data[10] == 1 && checkBits<6>(data, 1, 0b100001)) {
            shru = std::make_shared<SHRU>(dspInstInfo->getAddress(), baseCycle);
            shru->isCompactInstruction = true;
            shru->compactInstKind = "Ssh5";
            shru->cst = extractBits<3>(data, 13).to_ulong();
            shru->auxCst = extractBits<2>(data, 11).to_ulong() << 3;
            shru->src2 = shru->dst = extractBits<3>(data, 7).to_ulong();
            shru->s = data[0];
            if (shru->s == 0) {
                shru->funcUnit = FuncUnit::S1;
            } else {
                shru->funcUnit = FuncUnit::S2;
            }
            shru->DSZ = dspInstInfo->getDSZ();
            shru->RS = dspInstInfo->getRS();
            shru->SAT = dspInstInfo->getSAT();
            shru->PROT = dspInstInfo->getPROT();
            shru->BR = dspInstInfo->getBR();
            shru->p = dspInstInfo->getP();
            shru->fixUpRegOnCompactInstruction();
            shru->instFormat = InstFormat::Kind3;
        }
    }
    return shru;
}

void SHRU::executeCustom(std::shared_ptr<TargetMachine> targetMachine, ExecutePhase executePhase) {

}

std::shared_ptr<DspInstruction> SHRU::clone() {
    return std::make_shared<SHRU>(*this);
}

std::string SHRU::toString() const {
    std::string res;
    if (!isCompactInstruction) {
        res += getStandardConditionString() + " ";
    }
    res += m_name + " " + FuncUnitName[static_cast<u32>(funcUnit)] + " ";
    switch (instFormat) {
        case InstFormat::Kind1:
            res += getSrc2Reg32Name() + "," + getSrc1Reg32Name() + "," + getDstReg32Name();
            break;
        case InstFormat::Kind3:
            res += getSrc2Reg32Name() + "," + std::to_string(cst) + "," + getDstReg32Name();
            break;
        default:
            break;
    }
    return res;
}

void SHRU::updateContextBeforeExecute(std::shared_ptr<TargetMachine> targetMachine, std::shared_ptr<LLVMJit> llvmJit) {
    std::shared_ptr<DspMachine> dspMachine = std::dynamic_pointer_cast<DspMachine>(targetMachine);
    // 指令执行之前，设置pce1寄存器，使pce1寄存器的值为当前执行的指令所在的取指包的第一条指令的地址
    auto pce1Reg = targetMachine->getRegisters()->getReg32ByName("PCE1");
    pce1Reg->updateData(getInstructionAddress() - getInstructionAddress() % 0x20);

    updateRegAndCstPtr(dspMachine->getSaveRegs(), dspMachine->getRegisters());
    if (instFormat == InstFormat::Kind1 || instFormat == InstFormat::Kind2)
        cst = computeSHRUNumBySrc1(dspMachine);
}

u32 SHRU::computeSHRUNumBySrc1(std::shared_ptr<DspMachine> dspMachine) {
    u32 src1Reg = *src1LoRegPtr;
    auto src1RegLSB6 = src1Reg & 0x0000003f;
    return src1RegLSB6 > 39 ? 40 : src1RegLSB6;
}
